import markdown
from django.core.paginator import Paginator, EmptyPage
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic.base import View

from web.models import Article, Category, Tag


class IndexView(View):

    def get(self, request):

        art_list = Article.objects.all()
        cate_list = Category.objects.all()
        tag_list = Tag.objects.all()
        top10 = art_list[:10]

        # 对数据分页
        page_size = request.GET.get('page_size', 10)
        page_num = request.GET.get('page_num', 1)
        paginator = Paginator(art_list, page_size)
        try:
            page_articles = paginator.page(page_num)
        except EmptyPage:
            page_articles = []
        total_page = paginator.num_pages

        context = {
            'art_list': page_articles,
            'cate_list': cate_list,
            'tag_list': tag_list,
            'total_page': total_page,
            'top10': top10,
            'page_num': page_num,
            'page_size': page_size,
        }

        return render(request, 'index.html', context)


class ArticleDetail(View):
    """文章详情"""

    def get(self, request, aid):

        art_obj = Article.objects.filter(id=aid).first()
        art_obj.content = markdown.markdown(art_obj.content, extensions=[
                                                  'markdown.extensions.extra',
                                                  'markdown.extensions.codehilite',
                                                  'markdown.extensions.toc',
                                              ])
        context = {
            'art_obj': art_obj,
            'cate': art_obj.category,
            'tag_list': art_obj.tags.all(),
        }
        return render(request, 'article_detail.html', context)


class Test(View):
    def get(self, request):
        print('-------------------------------')
        return HttpResponse('test')
